package org.jeecg.modules.strategy.component;


import com.alibaba.druid.util.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.strategy.model.query.AnalyticsQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Spider;

@Component
public class HomePageSpider {
    private final HomePagePipeline homePagePipeline;
    private final HomePagePageProcessor homePagePageProcessor;
    private Spider spider;

    @Autowired
    public HomePageSpider(HomePagePipeline homePagePipeline, HomePagePageProcessor homePagePageProcessor) {
        this.homePagePipeline = homePagePipeline;
        this.homePagePageProcessor = homePagePageProcessor;
        this.spider = Spider.create(homePagePageProcessor)
                .addPipeline(homePagePipeline)
                .thread(5);
    }

    public String startCollectHomePageMetaTask(AnalyticsQuery analyticsQuery) {
        if (!StringUtils.isEmpty(analyticsQuery.getUrl())) {
            spider = this.spider.addUrl(analyticsQuery.getUrl());
            spider.run();
            return "success";
        }
        return "error";
    }

    public String stopCollectHomePageMetaTask() {
        if (spider != null) {
            spider.stop();
            return "success";
        }
        return "error";
    }
}
